import * as Blockly from 'blockly';
import { CustomFunction } from '../../services/custom-function.service';

// 跟踪已注册的自定义函数块
const registeredCustomBlocks = new Set<string>();

export function registerCustomFunctionBlock(customFunction: CustomFunction) {
  const blockName = `custom_function_${customFunction.name}`;
  
  // 如果已经注册过这个块，直接返回块名
  if (registeredCustomBlocks.has(blockName)) {
    console.log(`Block ${blockName} already registered, skipping registration`);
    return blockName;
  }
  
  // 创建块定义
  const blockDefinition: any = {
    type: blockName,
    message0: customFunction.name,
    args0: [],
    colour: 290,
    tooltip: `自定义函数: ${customFunction.name}`,
    helpUrl: '',
  };
  
  // 添加参数输入
  customFunction.params.forEach((param, index) => {
    blockDefinition[`message${index + 1}`] = `${param}: %1`;
    blockDefinition[`args${index + 1}`] = [
      {
        type: 'input_value',
        name: `PARAM_${index}`,
        align: 'RIGHT',
      },
    ];
  });
  
  // 设置输出或前后连接
  if (customFunction.hasReturnValue) {
    blockDefinition.output = null; // 允许任何类型的输出
  } else {
    blockDefinition.previousStatement = null;
    blockDefinition.nextStatement = null;
  }
  
  // 注册块定义
  try {
    Blockly.common.defineBlocks({
      [blockName]: {
        init: function() {
          this.jsonInit(blockDefinition);
        }
      }
    });
    // 标记为已注册
    registeredCustomBlocks.add(blockName);
    console.log(`Block ${blockName} registered successfully`);
  } catch (e) {
    console.warn(`Error registering block ${blockName}:`, e);
  }
  
  return blockName;
}

export function registerCustomFunctionBlocks(customFunctions: CustomFunction[]) {
  return customFunctions.map(func => registerCustomFunctionBlock(func));
}